package com.nowcoder.community.community.controller.advice;

import com.nowcoder.community.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

// ()内容表示：扫描带有Controller注解的Bean
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler({Exception.class})
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 记录异常的概括
        logger.error("服务器发生异常：" + e.getMessage());
        // 记录详细的栈中异常
        for (StackTraceElement element : e.getStackTrace()){
            logger.error(element.toString());
        }

        // 给浏览器响应（响应前需要判断请求的方式）
        String xRequestedWith = request.getHeader("x-requested-with");
        if("XMLHttpRequest".equals(xRequestedWith)){
            // 异步请求，向浏览器响应字符串
            response.setContentType("application/plain;charset=utf-8");// "plain"表示普通字符串，也可"json"表示json字符串
            PrintWriter writer = response.getWriter();
            writer.write(CommunityUtil.getJSONString(1,"服务器异常！"));
        } else {
            // 普通请求，向浏览器响应html页面
            response.sendRedirect(request.getContextPath() + "/error");
        }
    }

}
